﻿using JWT;
using JwtApiDemo.Comm;
using JwtApiDemo.Helper;
using JwtApiDemo.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;

namespace JwtApiDemo.Controllers
{
    /// <summary>
    /// Jwt获取token
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class JwtController : ControllerBase
    {

        private readonly ILogger<JwtController> _logger;

        public JwtController(ILogger<JwtController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult CreateToken(string username, string pwd)
        {
            TokenResult result = new TokenResult();
            result.token = "";
            result.success = false;
            if (username != "" && pwd != "")
            {
                var userInfo = RamData.Instance.UserInfos.Find(p => p.username == username);
                if (userInfo == null)
                {
                    return new JsonResult(new OperationResult(OperationResultType.Error, "您登录的用户不存在"));
                }
                else
                {
                    if (userInfo.pwd != pwd)
                    {
                        return new JsonResult(new OperationResult(OperationResultType.Error, "您登录的用户密码不正确"));
                    }
                }

                IDateTimeProvider provider = new UtcDateTimeProvider();
                var now = provider.GetNow();
                var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
                var payload = new Dictionary<string, object>
                {
                    { "username",username },
                    { "pwd", pwd },
                    { "exp", secondsSinceEpoch + 60*30 } //失效时间秒  此处设置30分钟
                };

                result.token = JwtHelper.SetJwtEncode(payload);
                result.success = true;
                result.message = "生成token成功";
            }
            else
            {
                result.message = "用户名或者密码不能为空";
            }

            return new JsonResult(new OperationResult(OperationResultType.Success, "获取Token成功",result));
        }

    }
}
